package com.fengye.cluster.impl;

import com.fengye.cluster.ClusterStrategy;
import com.fengye.model.ProviderService;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 软负载轮询算法
 *
 * @Author fengye
 * @Date 2023/2/15 11:25
 **/
public class PollingClusterStrategyImpl extends AbstractClusterStrategt {
    /** 计数器 */
    private AtomicInteger count = new AtomicInteger(0);
    /** 锁 */
    private Lock lock = new ReentrantLock();

    @Override
    public ProviderService doSelect(List<ProviderService> providerServiceList) {
        ProviderService providerService = null;

        try {
            // 先获取一次锁，如果获取不到，等待时间再去一次
            if(lock.tryLock() || lock.tryLock(10, TimeUnit.MICROSECONDS)) {
                if (count.intValue() > providerServiceList.size()) {
                    // 轮询重设0
                    count.compareAndSet(count.intValue(), 0);
                }
                providerService = providerServiceList.get(count.intValue());
                count.getAndIncrement();
            }

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }

        return providerService;
    }
}
